var express = require('express');
var router = express.Router();
var mysql = require('./mysqlConfig');
// var redis = require('./redisServer');
var register = require('babel-core/register')
var config = require("../config.json");
/* 微信登陆 */
var AppID = config.wechat.appID;
var AppSecret = config.wechat.appSecret;

router.get('/autoLogin', function(req, res, next) {
    var info = req.query.info;
    var router;
    if (info) {
        router = 'get_wx_access_token?info=' + info;
    } else {
        router = 'get_wx_access_token';
    }
    // 第一步：用户同意授权，获取code

    // var url = "http://woniuchiyumi.top/demo/index.html/"
    var url = "http://10.10.50.80:3000/wx/"
    // 这是编码后的地址 host+app.js定义的路由最后要加/
    var return_uri = "http%3a%2f%2f10.10.50.80%3a3000%2fwx%2f" + router;

    var scope = 'snsapi_userinfo';
    res.redirect('https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + AppID + '&redirect_uri=' + return_uri + '&response_type=code&scope=' + scope + '&state=STATE#wechat_redirect');
});
router.get('/get_wx_access_token', function(req, res, next) {
    // 第二步：通过code换取网页授权access_token
    var code = req.query.code;
    var info = req.query.info;
    request.get({
            url: 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' + AppID + '&secret=' + AppSecret + '&code=' + code + '&grant_type=authorization_code',
        },
        function(error, response, body) {
            if (response.statusCode == 200) {
                // 第三步：拉取用户信息(需scope为 snsapi_userinfo)
                var data = JSON.parse(body);
                var access_token = data.access_token;
                var openid = data.openid;

                request.get({
                        url: 'https://api.weixin.qq.com/sns/userinfo?access_token=' + access_token + '&openid=' + openid + '&lang=zh_CN',
                    },
                    function(error, response, body) {
                        if (response.statusCode == 200) {
                            // 第四步：根据获取的用户信息进行对应操作
                            var userinfo = JSON.parse(body);
                            var uid = "'" + userinfo.openid + "'";
                            var name = "'" + userinfo.nickname + "'";
                            var openid = "'" + userinfo.openid + "'";
                            var sex = "'" + userinfo.sex ? userinfo.sex : 3 + "'";
                            var headimgurl = "'" + userinfo.headimgurl + "'";
                            console.log(body);
                        } else {

                        }
                    }
                );
            } else {

            }
        }
    );
});


module.exports = router;